package govenor.replicator;

import govenor.manager.GovenorManager;
import govenor.overwatch.FileStoreNode;
import govenor.overwatch.OverWatcher;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ReplicationHandler implements Runnable {

	private GovenorManager manager;
	private OverWatcher watcher;
	
	public ReplicationHandler(GovenorManager manager) {
		this.manager = manager;
		this.watcher = manager.getSystemWatcher();
	}
	
	public void run() {
		Map<String,String> mapOfFilenamesToServerIds = this.watcher.getAllFilesStored();
		//setServer IDs and split them, if the length is > 2 then there is a 2nd host
		Set<String> fileNameSet = mapOfFilenamesToServerIds.keySet();
		Iterator<String> iter = fileNameSet.iterator();
		while(iter.hasNext()){
			String filename = iter.next();
			String serverIds = mapOfFilenamesToServerIds.get(filename);
			String[] serverIdsSplit = serverIds.split(":");
			if(serverIdsSplit != null && serverIdsSplit.length < 3){
				//This means there is only one host for the file
				//Need to find a new host, first check there are more than 1 File Stores available
				if(this.watcher.getNumberOfFileStores() > 1){
					System.out.println("Finding best host");
					String hostId = serverIds;
					FileStoreNode hostNode = this.watcher.getFileStoreNodeFromFileStore(hostId);
					String serverId = this.watcher.findBestFileStore();
					FileStoreNode destinationHostNode = this.watcher.getFileStoreNodeFromFileStore(serverId);
					System.out.println("Replication request for: "+filename+" sent");
					this.manager.sendFileReplicationRequest(hostNode.getCommandNetworkDescription().getHostname(),hostNode.getCommandNetworkDescription().getPortNumber(),filename,destinationHostNode.getFileUploadNetworkDescription().getHostname(),destinationHostNode.getFileUploadNetworkDescription().getPortNumber());
				}else{
					System.out.println("No file stores available to replicate");
				}
			}else{
				System.out.println("No Replication required for file: "+filename);
			}
		}
	}

}
